package com.kjlink.internal.report4vue.config;

import cn.dev33.satoken.interceptor.SaInterceptor;
import cn.dev33.satoken.stp.SaLoginModel;
import cn.dev33.satoken.stp.StpUtil;
import cn.xuqiudong.common.base.tool.Tools;
import com.kjlink.internal.workreport.helper.SessionHelper;
import com.kjlink.internal.workreport.system.service.SystemService;
import com.kjlink.internal.workreport.user.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;


/**
 * web相关的一些配置
 *
 * @author Vic.xu
 * @since 2024-04-30
 */
@Configuration
public class ApiWebConfig implements WebMvcConfigurer {

    @Autowired
    private SystemService systemService;


    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //1. 权限拦截器
//        InterceptorRegistration registration = registry.addInterceptor(new ApiTokenInterceptor());
//        registration.addPathPatterns("/api/**").excludePathPatterns("/api/login");/**/


        // 注册 Sa-Token 拦截器，校验规则为 StpUtil.checkLogin() 登录校验。
        registry.addInterceptor(new SaInterceptor(handle -> {
                    // 补充session信息：当sa-token 存在 但是session中不存在的情况
                    if (StpUtil.isLogin()) {
                        User user = SessionHelper.currentUser();
                        if (user == null) {
                            systemService.loginById(StpUtil.getLoginIdAsInt());
                        }
                    } else {
                        //等sa-token 判断没有登录的时候 从token中解析中用户然后登录
                        User user = systemService.ifLogin(Tools.currentRequest());
                        if (user != null) {
                            try {
                                SaTokenConfigure.setCurrentSaToken(StpUtil.getTokenValue());
                                // 以指定cookie登录
                                // https://sa-token.cc/doc.html#/api/stp-util
                                SaLoginModel model = new SaLoginModel()
                                        .setToken(StpUtil.getTokenValue())
                                        .setIsLastingCookie(true);
                                StpUtil.login(user.getId(), model);
                                SessionHelper.storeUser(user);
                            } finally {
                                SaTokenConfigure.removeCurrentSaToken();
                            }

                        }
                    }
                    StpUtil.checkLogin();
                }))
                .addPathPatterns("/api/v1/**")
                .excludePathPatterns("/test/**")
                .excludePathPatterns("/api/v1/users/login");


    }
}
